<?php

namespace app\api\controller;

use app\common\controller\Api;
use fast\Random;
use fast\Tree;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 商品接口
 */
class Goods extends Api
{
    protected $noNeedLogin = ['goodsClass','goodslist','goodsinfo'];
    protected $noNeedRight = ['*'];

    /**
     * Goods模型对象
     * @var \app\admin\model\Goods
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Goods;

//        $goodsClassList = collection(\app\admin\model\GoodsClass::select())->toArray();
//
//        Tree::instance()->init($goodsClassList);
//
//        $goodsClassList = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
//
//
//        $goodsClassName = [];
//        foreach ($goodsClassList as $k => $v) {
//            $goodsClassName[$v['id']] = $v['name'];
//        }
//
//        $this->goodsClassList = $goodsClassList;
//        $this->goodsClassData =  $goodsClassName;

//        $this->view->assign('goods_class_data', $this->goodsClassData);
    }

    /**
     * 商品列表
     */
    public function index()
    {
        $admin_id= $this->auth->getUserinfo()['id'];
        $where['admin_id']=['=',$admin_id];
        $goods_state = $this->request->post("goods_state");
        if($goods_state){
            $where['goods_state']=['=',$goods_state];
        }

        $goodsRe = $this->model
            ->where($where)
            ->paginate(10);

        $this->success(__('获取成功'), $goodsRe);
    }

    /**
     * 添加
     */
    public function add()
    {
        $params= $this->request->param();
        $params=array_filter($params);
        if(!isset($params['title'])|| !isset($params['goods_class_id'])|| !isset($params['goods_image'])|| !isset($params['goods_describe'])||  !isset($params['state'])|| !isset($params['goods_price'])|| !isset($params['stock'])|| !isset($params['collection_cycle'])){
            $this->error(__('缺少必填参数'));
        }

        $params['admin_id']=$this->auth->getUserinfo()['id'];

        if ($params) {
            $result = false;
            Db::startTrans();
            try {
                $result = $this->model->allowField(true)->save($params);

                Db::commit();
            } catch (ValidateException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $params['id']=$this->model->id;
                $this->success('添加成功',$params);
            } else {
                $this->error(__('No rows were inserted'));
            }
        }


    }

    /**
     * 编辑
     */
    public function edit()
    {
        $admin_id= $this->auth->getUserinfo()['id'];
        $goods_id= $this->request->post("goods_id");

        $params= $this->request->param();

        $row = $this->model->where('id',$params['goods_id'])->where('admin_id',$params['admin_id'])->find();

        if (!$row) {
            $this->error(__('未找到数据'));
        }

        $params=array_diff_key($params, ["admin_id"=>"xy", "goods_id"=>"xy"]);
        $params=array_filter($params);

        if ($params) {
            $result = false;
            Db::startTrans();
            try {
                $result = $row->allowField(true)->save($params);
                Db::commit();
            } catch (ValidateException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success('修改成功',$params);
            } else {
                $this->error(__('No rows were updated'));
            }
        }

        $this->success('获取成功',$row);

    }
    /**
     * 删除
     */
    public function del()
    {
        $admin_id= $this->auth->getUserinfo()['id'];
        $goods_id= $this->request->post("goods_id");
        if($admin_id && $goods_id) {
            Db::startTrans();
            try {
                $delre = $this->model->where('id', $goods_id)->where('admin_id', $admin_id)->delete();
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($delre) {
                $this->success();
            } else {
                $this->error(__('未删除任何数据'));
            }
        }else{
                $this->error(__('缺少参数'));
        }
    }
	
    /**
     * 商品分类（B C）
     */
    public function goodsClass()
    {
        $goodsClassList = collection(\app\admin\model\GoodsClass::select())->toArray();

        $items=array();
        foreach($goodsClassList as $v){ //将数组存入$items,且$items的键为$data中的id
            $items[$v['id']] = $v;
        }

        $tree=array();
        foreach($items as $item){
            if(isset($items[$item['pid']])){ //通过pid判断$items中是否有对应的数组,$items[0]不存在
                $items[$item['pid']]['child'][]=&$items[$item['id']];
            }else{
                $tree[]=&$items[$item['id']];
            }
        }

        $this->success('获取成功',$tree);

    }

    /**
     * 商品列表页（B C）
     */
    public function goodslist()
    {

        $goods_class_id= $this->request->post("goods_class_id");

        $where['goods_class_id']=['=',$goods_class_id];
        $where['state']=['=',1];
        $where['stock']=['>',0];

        $goodslist=\app\admin\model\Goods::where($where)->paginate(10);

        if($goodslist){
            $this->success('获取成功',$goodslist);
        }else{
            $this->error('未找到商品分类');
        }
    }


    /**
     * 商品详情页（B C）
     */
    public function goodsinfo()
    {
        $goodsid= $this->request->post("goodsid");

        $where['id']=['=',$goodsid];
        // $where['state']=['=',1];
        // $where['stock']=['>',0];

        $goodsinfo=\app\admin\model\Goods::where($where)->find();
        if($goodsinfo){
            $this->success('获取成功',$goodsinfo);
        }else{
            $this->error('未找到商品');
        }


    }















}
